package com.hyjx.framework.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet implementation class QRCodeServlet
 */
public class QRCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public QRCodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String content = request.getParameter("content");
        if (content == null) return;
        String size = request.getParameter("size");
        int sizeint = 7;
        if (!StringUtils.isEmpty(size))
            sizeint = Integer.parseInt(size);
        String logo = request.getParameter("logo");
        String c = new String(content.getBytes("iso8859-1"), "utf-8");
        if (StringUtils.isNoneEmpty(content)) {
            byte qrbytes[] = null;
            if (logo == null || logo.trim().length() == 0) {
                qrbytes = QRCodeUtil.encoderQRCodeAsByteArray(c, QRCodeUtil.PNG, sizeint);
            } else {
                qrbytes = QRCodeUtil.encoderQRCodeAsByteArray(c, QRCodeUtil.PNG, sizeint, logo);
            }
            ServletOutputStream sos = response.getOutputStream();
            sos.write(qrbytes);
            sos.flush();
            sos.close();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
